package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/5 21:44
 * @注释
 */
public class MultiConsumer {
    private static final String QUEUE_NAME = "multi_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("111.229.199.44");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);
        final Connection connection = factory.newConnection();
        for(int i=0;i<2;i++){
            final Channel channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            System.out.println(" [*] Waiting for message.To exit press");
            channel.basicQos(1);
            int finalI=i;
            DeliverCallback deliverCallback=(consumerTag, delivery) ->{
                String message = new String(delivery.getBody(), "UTF-8");
                try {
                    System.out.println(" [x] Received " +"编号"+finalI+" '" +message + "'");
                    Thread.sleep(20000);
                }catch (Exception e){
                    e.printStackTrace();
                } finally {
                    System.out.println(" [x] Done");
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                }
            } ;
            channel.basicConsume(QUEUE_NAME,false,deliverCallback,consumerTag -> { });
        }

    }
   /* private static void doWork(String task){
        for(char ch:task.toCharArray()){
            if(ch=='.'){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }*/
}
